package cn.gqr.controller.fore;

import cn.gqr.entity.Hot;
import cn.gqr.entity.Largefile;
import cn.gqr.entity.NewBook;
import cn.gqr.entity.User;
import cn.gqr.service.BookService;
import cn.gqr.service.HotService;
import cn.gqr.service.PublicService;
import cn.gqr.service.TypeService;
import cn.gqr.tool.GetUser;
import cn.gqr.tool.RespJson;
import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

//公共的
@Controller
@RequestMapping("/api/public")
public class PublicController {

    @Autowired
    PublicService publicService;
    @Autowired
    HotService hotService;
    @Autowired
    BookService bookService;
    @Autowired
    TypeService typeService;


    //获取热点对象Hot,根据typeid查询
    @ResponseBody
    @RequestMapping("/findHot/{num}/{type}")
    public Map<String,Object> findHot(@PathVariable("num") int num,@PathVariable("type") int type){
        List<Hot> hots = publicService.findHot(num, type);
        return RespJson.pack(200,"ok",hots);
    }

    //模糊查询
    @ResponseBody
    @PostMapping("/book/findIf/{start}/{num}")
    public Map<String,Object> findIf( @PathVariable("start") int start,
                                      @PathVariable("num") int num,String key){
        //判断key值小于两个字返回空数据
        if(key.length()<2){
            return RespJson.pack(100,"搜素关键字不能小于2",null);
        }
        //模糊查找
        List<NewBook> books = publicService.findIf(start, num, key);
        //模糊查找总行数
        int total = publicService.findByLine(start, num, key);

        //查找的数据为空
        if(books.isEmpty()){
            return RespJson.pack(200,"无数据",null);
        }

        Map map = new HashMap();
        map.put("total",total);
        String str ="<span style='color:red;'>"+key+"</span>";
        //循环每一个book
        for (NewBook b :books){
            //判断这条数据那个字段包含了key这个字符串;
            if(b.getPublisher()!=null && b.getPublisher().matches(".*"+key+".*")){
                b.setPublisher(b.getPublisher().replace(key,str));
            }
            if(b.getName()!=null&&b.getName().matches(".*"+key+".*")){
                b.setName(b.getName().replace(key,str));
            }
            if(b.getAuthor()!=null&&b.getAuthor().matches(".*"+key+".*")){
                b.setAuthor(b.getAuthor().replace(key,str));
            }
        }
        map.put("books",books);
        return RespJson.pack(200,"匹配成功",map);
    }


    //分页查找书本信息,起始页start ,每页num行,
    // 条件 typeid >0 根据typeid查询,
    //typeid==0 typeid不生效,查询全部数据
    @ResponseBody
    @RequestMapping("/findBookByPage/{start}/{num}/{typeid}")
    public Map<String,Object> findHot(@PathVariable("start") int start,
                                      @PathVariable("num") int num,@PathVariable("typeid") int typeid){
        List<NewBook> books = publicService.findBookByPage(start,num,typeid);
        return addTotal(books,typeid);
    }


    //添加user
    @ResponseBody
    @RequestMapping("/addUser")
    public Map<String,Object> addUser(User u){
        return publicService.addUser(u);
    }

    //获取user
    @ResponseBody
    @GetMapping("/getUser")
    public Object getUser(){
        return GetUser.getUser();
    }


    //produces = MediaType.IMAGE_JPEG_VALUE  告诉springboot我要返回的是一个图片
    @ResponseBody
    @RequestMapping(value = "/showImg/{id}",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] showImg(@PathVariable("id")String id){
        //根据uuid查找,返回一个Largefile对象
        Largefile obj = hotService.findByPicture(id);
        if(obj==null){
            System.out.println("图片id空");
            return null;
        }
        //把object转换为byte[]
        byte[] buf  = (byte[])obj.getContent();
        return buf;
    }


    //查找所有的书本类型
    @ResponseBody
    @RequestMapping("/type/findAll")
    public Map<String,Object> findAll(){
        return RespJson.pack(200,"ok",typeService.findAll());
    }


    //根据bookid查询的book对象的rate属性加1
    @ResponseBody
    @RequestMapping("/book/addRate/{bookid}")
    public Map<String,Object> addRate(@PathVariable("bookid") int bookid){
        publicService.addRate(bookid);
        return RespJson.pack(200,"点赞加分",null);
    }

    //升序全查询
    @ResponseBody
    @RequestMapping("/type/findAll2")
    public Map<String,Object> findAll2(){
        return RespJson.pack(200,"",publicService.findAll2());
    }

    //获取点赞前五的book对象
    @ResponseBody
    @RequestMapping("/book/findRate5")
    public Map<String,Object> findRate5(){
        return RespJson.pack(200,"点赞前五",publicService.findBefore5("rate"));
    }


    //获取销量前五的book对象
    @ResponseBody
    @RequestMapping("/book/findSale5")
    public Map<String,Object> findSale5(){
        return RespJson.pack(200,"销量前五",publicService.findBefore5("salenum"));
    }


    //获取点加入购物车前五的book对象
    @ResponseBody
    @RequestMapping("/book/findFav5")
    public Map<String,Object> findFav5(){
        return RespJson.pack(200,"点加入购物车前五",publicService.findBefore5("favnum"));
    }


    //分页查找书本信息并按照点赞从高到低排序,
    //并且可按照类型(typeid==0 时, 类型查询不生效)
    @ResponseBody
    @RequestMapping("/findBookByPageRate/{start}/{num}/{typeid}")
    public Map<String,Object> findBookByPageRate(@PathVariable("start") int start,
                                                 @PathVariable("num") int num,@PathVariable("typeid") int typeid){
        List<NewBook> books = publicService.findBookByPageTerm("rate",start,num,typeid);
        return addTotal(books,typeid);
    }


    //分页查找书本信息并按照销量从高到低排序,
    //并且可按照类型(typeid==0 时, 类型查询不生效)
    @ResponseBody
    @RequestMapping("/findBookByPageSale/{start}/{num}/{typeid}")
    public Map<String,Object> findBookByPageSale(@PathVariable("start") int start,
                                                 @PathVariable("num") int num,@PathVariable("typeid") int typeid){

        List<NewBook> books = publicService.findBookByPageTerm("salenum",start,num,typeid);
        return addTotal(books,typeid);
    }


    //分页查找书本信息并按照购物车从高到低,
    //并且可按照类型(typeid==0 时, 类型查询不生效)
    @ResponseBody
    @RequestMapping("/findBookByPageFav/{start}/{num}/{typeid}")
    public Map<String,Object> findBookByPageFav(@PathVariable("start") int start,
                                                @PathVariable("num") int num,@PathVariable("typeid") int typeid){
        List<NewBook> books = publicService.findBookByPageTerm("favnum",start,num,typeid);
        return addTotal(books,typeid);
    }


    //添加行数属性total进map，并返回JSON格式数据
    //只适用于有typeid条件的分页查询
    public Map addTotal(List<NewBook> books,int typeid){
        Map map = new HashMap();
        if(books.isEmpty()) {
            return RespJson.pack(204,"无数据",null);
        }
        map.put("books",books);
        //typeid>0 表示需要typeid作为条件排序查询 ，需要返回条件查询后的数据行数
        map.put("total",publicService.findLineByTypeid(typeid));
        //typeid==0或者小于0 表示进行无条件查询 返回总数据的行数
        if(typeid==0 || typeid<0){
            map.put("total",bookService.findByLine());
        }
        return RespJson.pack(200,"ok",map);
    }

    

//    //短信平台相关参数
//    private String apiUrl = "https://sms_developer.zhenzikj.com";
//    //榛子云系统上获取
//    private String appId = "110657";
//    private String appSecret = "3f9440e1-9e3f-4a62-8892-0c4dac3a9599";
//
//    @ResponseBody
//    @RequestMapping("/sendCode")    //生成验证码并存储在session
//    public boolean getCode(String memPhone, HttpSession httpSession){
//        System.out.println(memPhone);
//        try {
//            JSONObject json = null;
//            //随机生成验证码
//            String code = String.valueOf(new Random().nextInt(999999));
//            //将验证码通过榛子云接口发送至手机
//            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
//            Map<String, Object> params = new HashMap<String, Object>();
//            //前台输入的手机号
//            params.put("number", memPhone);
//            //是榛子云个人中心的短信模板id
//            params.put("templateId", 7774);
//            String[] templateParams = new String[2];
//            templateParams[0] = code;
//            templateParams[1] = "5分钟";
//            params.put("templateParams", templateParams);
//            String result = client.send(params);
//            System.out.println(result);
//            json = JSONObject.parseObject(result);
//            if (json.getIntValue("code")!=0){//发送短信失败
//                return  false;
//            }
//            //将验证码存到session中,同时存入创建时间
//            //以json存放，这里使用的是阿里的fastjson
//            json = new JSONObject();
//            json.put("memPhone",memPhone);
//            json.put("code",code);
//            json.put("createTime",System.currentTimeMillis());
//            // 将认证码存入SESSION
//            httpSession.setAttribute("code",json);
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }
//
//    @ResponseBody
//    @RequestMapping("/register") //手机号注册
//    public Map<String,Object> register(String phone,String phoneCode,HttpSession session){
//        return publicService.register(phone,phoneCode,session);
//    }
}